package cn.team11.smarteye.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.List;

/**
 * Created by Yang on 2017/10/30.
 * RecyclerView的通用适配器定义
 */

public abstract class CommonAdapter<T> extends RecyclerView.Adapter<CommonViewHolder> implements View.OnClickListener, View.OnLongClickListener {

    protected Context mContext;
    protected int mLayoutId;
    protected List<T> mDatas;
    protected LayoutInflater mInflater;

    private OnItemClickListener onItemClickListener;
    private OnItemLongClickListener onItemLongClickListener;

    public CommonAdapter(Context mContext, int mLayoutId, List<T> mDatas) {
        this.mContext = mContext;
        this.mLayoutId = mLayoutId;
        this.mDatas = mDatas;
        this.mInflater = LayoutInflater.from(mContext);
    }

    @Override
    public void onBindViewHolder(CommonViewHolder holder, int position) {
        //将position保存在itemView的Tag中，以便点击时进行获取
        holder.getConvertView().setTag(position);
        convert(holder, mDatas.get(position));
    }

    @Override
    public CommonViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(mContext).inflate(mLayoutId, parent, false);
        itemView.setOnClickListener(this);
        itemView.setOnLongClickListener(this);
        CommonViewHolder holder = CommonViewHolder.createViewHolder(mContext, itemView);
        return holder;
    }

    public abstract void convert(CommonViewHolder holder, T t);


    @Override
    public int getItemCount() {
        return mDatas.size();
    }


    /**
     * 给recyclerview添加点击事件
     * */
    public interface OnItemClickListener {
        void onItemClick(View view, int position);
    }

    public interface OnItemLongClickListener {
        void onItemLongClick(View view, int position);
    }


    @Override
    public void onClick(View view) {
        if (onItemClickListener != null){
            onItemClickListener.onItemClick(view, (int) view.getTag());
        }
    }

    @Override
    public boolean onLongClick(View view) {
        if (onItemLongClickListener != null){
            onItemLongClickListener.onItemLongClick(view, (int)view.getTag());
        }
        return false;
    }


    public void setOnItemClickListener(OnItemClickListener listener){
        this.onItemClickListener = listener;
    }

    public void setOnItemLongClickListener(OnItemLongClickListener listener){
        this.onItemLongClickListener = listener;
    }
}
